package com.fyp.client.ptma;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

import com.fyp.client.ptma.utils.Helper;
import com.fyp.client.ptma.utils.NetworkConnectivity;
import com.fyp.client.ptma.xml.XmlBuilder;

public class PackageReceiver extends BroadcastReceiver
{
	private static Context cotx;

	@Override
	public void onReceive(Context ctx, Intent intent)
	{
		cotx = ctx;

		Bundle b = intent.getExtras();
		int uid = b.getInt(Intent.EXTRA_UID);
		String[] packages = ctx.getPackageManager().getPackagesForUid(uid);

		SharedPreferences prefs = ctx.getSharedPreferences(
				Constants.SHARED_PREFERENCE, Context.MODE_PRIVATE);

		prefs.getString(Constants.PREF_KEY_CURRENT_PACKAGE, null);
		if (Helper.notification != null)
		{
			String pkg = Helper.notification.getAppVersion().getVersionPk()
					.getApplication().getNameSpace();
			if (null != pkg && pkg.equals(packages[0]) || BuildConfig.DEBUG)
			{
				new NotifyServer().execute(ctx);

			}
		}

		System.out.println("onReceive");
	}

	private static final class NotifyServer extends
			AsyncTask<Object, Integer, Integer>
	{
		@Override
		protected void onPostExecute(Integer result)
		{
			Toast.makeText(cotx, "Status updated", Toast.LENGTH_LONG).show();
		}

		@Override
		protected Integer doInBackground(Object... params)
		{
			Context ctx = (Context) params[0];

			String url = ctx.getString(R.string.WS_URL)
					+ ctx.getString(R.string.WS_APPDOWNLOADED);
			NetworkConnectivity.performPostOperation(url, XmlBuilder
					.getXmlForUpdateDownloadStatus(Helper.notification));
			Helper.notification = null;

			return 0;
		}

	}

}